package com.hdax.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hdax.common.constant.ProductConstant;
import com.hdax.common.utils.R;
import com.hdax.gulimall.product.dao.PmsAttrAttrgroupRelationDao;
import com.hdax.gulimall.product.dao.PmsAttrGroupDao;
import com.hdax.gulimall.product.dao.PmsCategoryDao;
import com.hdax.gulimall.product.entity.*;
import com.hdax.gulimall.product.service.PmsAttrAttrgroupRelationService;
import com.hdax.gulimall.product.service.PmsAttrGroupService;
import com.hdax.gulimall.product.service.PmsCategoryService;
import com.hdax.gulimall.product.vo.AttrGroupRelationVo;
import com.hdax.gulimall.product.vo.AttrResponseVo;
import com.hdax.gulimall.product.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdax.common.utils.PageUtils;
import com.hdax.common.utils.Query;

import com.hdax.gulimall.product.dao.PmsAttrDao;
import com.hdax.gulimall.product.service.PmsAttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;


@Service("pmsAttrService")
public class PmsAttrServiceImpl extends ServiceImpl<PmsAttrDao, PmsAttrEntity> implements PmsAttrService {



    @Autowired
    private PmsAttrGroupDao pmsAttrGroupDao;

    @Autowired
    private PmsCategoryDao pmsCategoryDao;
    @Autowired
    private PmsAttrAttrgroupRelationDao pmsAttrAttrgroupRelationDao;

    @Autowired
    private PmsCategoryService pmsCategoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PmsAttrEntity> page = this.page(
                new Query<PmsAttrEntity>().getPage(params),
                new QueryWrapper<PmsAttrEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * 添加
     * @param attrVo
     */
    @Override
    public void saveAttr(AttrVo attrVo) {

        PmsAttrEntity pmsAttrEntity=new PmsAttrEntity();
        //赋值对象
        BeanUtils.copyProperties(attrVo,pmsAttrEntity);
        boolean save = this.save(pmsAttrEntity);
        //保存关联关系
        if(attrVo.getAttrType()== ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            PmsAttrAttrgroupRelationEntity pmsAttrAttrgroupRelationEntity=new PmsAttrAttrgroupRelationEntity();
            pmsAttrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            pmsAttrAttrgroupRelationEntity.setAttrId(pmsAttrEntity.getAttrId());
            pmsAttrAttrgroupRelationDao.insert(pmsAttrAttrgroupRelationEntity);
        }

    }



    /**
     * 根据分组属性的id来查询分组属性的内容，来进行修改
     * @param attrId
     * @return
     */
    @Override
    public AttrResponseVo getInfo(Long attrId) {
        AttrResponseVo attrResponseVo=new AttrResponseVo();
        PmsAttrEntity pmsAttrEntity = this.getById(attrId);
        BeanUtils.copyProperties(pmsAttrEntity,attrResponseVo);
/**
 * 分组信息的设置
 */
        //分组分数属性的关联表m, 根据分组id查询分组
        PmsAttrAttrgroupRelationEntity pmsAttrAttrgroupRelationEntity = pmsAttrAttrgroupRelationDao.selectOne(new QueryWrapper<PmsAttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        if(pmsAttrAttrgroupRelationEntity!=null){
            //从分组表中查询分组名称
            PmsAttrGroupEntity attrGroupEntity = pmsAttrGroupDao.selectById(pmsAttrAttrgroupRelationEntity.getAttrGroupId());
            if(attrGroupEntity!=null){
                attrResponseVo.setAttrGroupId(attrGroupEntity.getAttrGroupId());
            }
        }
        /**
         * 设置分类的信息
         */
        Long[] catelogPath = pmsCategoryService.findCatelogPath(attrResponseVo.getCatelogId());
        if(catelogPath!=null){
            attrResponseVo.setCatelogPath(catelogPath);
        }
        /**
         * 类别属性的设置
         */
//        PmsCategoryEntity pmsCategoryEntity = pmsCategoryDao.selectById(attrResponseVo.getCatelogId());
//        if(pmsCategoryEntity!=null){
//            attrResponseVo.setCatelogName(pmsCategoryEntity.getName());
//        }
        return attrResponseVo;
    }

    /**
     * 修改分组属性的数据
     * @param attrvo
     */
    @Transactional
    @Override
    public void updateAttr(AttrVo attrvo) {
        PmsAttrEntity pmsAttrEntity=new PmsAttrEntity();
        BeanUtils.copyProperties(attrvo,pmsAttrEntity);
        this.updateById(pmsAttrEntity);
        if(attrvo.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //修改数组属性关联的表
            PmsAttrAttrgroupRelationEntity pmsAttrAttrgroupRelationEntity = new PmsAttrAttrgroupRelationEntity();
            pmsAttrAttrgroupRelationEntity.setAttrGroupId(attrvo.getAttrGroupId());
            pmsAttrAttrgroupRelationDao.update(pmsAttrAttrgroupRelationEntity,new UpdateWrapper<PmsAttrAttrgroupRelationEntity>().eq("attr_id",attrvo.getAttrId()));

        }

    }

    @Override
    public PageUtils queryBaseAttrList(Map<String, Object> paramd, Long catelogId, String type) {
        QueryWrapper<PmsAttrEntity> queryWrapper=new QueryWrapper<PmsAttrEntity>().eq("attr_type","base".equalsIgnoreCase(type)?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if(catelogId!=0){
            queryWrapper.eq("catelog_id",catelogId);
        }

        String key = (String) paramd.get("key");
        if(!StringUtils.isEmpty(key)){
            //attr_id  attr_name
            queryWrapper.and((item)->{
                item.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<PmsAttrEntity> page=this.page(
                new Query<PmsAttrEntity>().getPage(paramd),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        //获取当前的组属性的集合，根据categoryid和attr_id name 查询
        List<PmsAttrEntity> records = page.getRecords();
        List<AttrResponseVo> attr_id = records.stream().map((item) -> {
            AttrResponseVo attrResponseVo = new AttrResponseVo();
            BeanUtils.copyProperties(item, attrResponseVo);
            if("base".equalsIgnoreCase(type)){
                //根据分组属性的id来查询关联表的组id
                PmsAttrAttrgroupRelationEntity pmsAttrAttrgroupRelationEntity = pmsAttrAttrgroupRelationDao.selectOne(
                        new QueryWrapper<PmsAttrAttrgroupRelationEntity>().eq("attr_id", item.getAttrId())
                );
                //获取组的id
                //根据组id查询组的name
                if (pmsAttrAttrgroupRelationEntity != null) {
                    PmsAttrGroupEntity attrGroupEntity = pmsAttrGroupDao.selectById(pmsAttrAttrgroupRelationEntity.getAttrGroupId());
                    attrResponseVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            //获取分类的name
            PmsCategoryEntity cat_id = pmsCategoryDao.selectById(item.getCatelogId());
            attrResponseVo.setCatelogName(cat_id.getName());
            return attrResponseVo;
        }).collect(Collectors.toList());
        pageUtils.setList(attr_id);
        return pageUtils;
    }


    /**
     *
     * @param attrgroupId
     * @return
     */
    @Override
    public List<PmsAttrEntity> getRelationAttr(Long attrgroupId) {
        LambdaQueryWrapper<PmsAttrAttrgroupRelationEntity> queryWrapper = new LambdaQueryWrapper<PmsAttrAttrgroupRelationEntity>()
                .eq(PmsAttrAttrgroupRelationEntity::getAttrGroupId, attrgroupId);
        List<PmsAttrAttrgroupRelationEntity> entities = pmsAttrAttrgroupRelationDao.selectList(queryWrapper);
        List<Long> collect = entities.stream().map(PmsAttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        List<PmsAttrEntity> pmsAttrEntities = CollectionUtils.isEmpty(collect) ? Collections.emptyList() : (List<PmsAttrEntity>) this.listByIds(collect);
        return pmsAttrEntities;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] attrGroupRelationVo) {

        List<AttrGroupRelationVo> attrGroupRelationVos = Arrays.asList(attrGroupRelationVo);
        List<PmsAttrAttrgroupRelationEntity> collect = attrGroupRelationVos.stream().map((item) -> {
            PmsAttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new PmsAttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, attrAttrgroupRelationEntity);
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());
        pmsAttrAttrgroupRelationDao.deleteBashchRelation(collect);
    }

    /**
     * 查询当前组没有关联的属性
     * @param attrgroupId
     * @param map
     * @return
     */
    @Override
    public PageUtils getNoAttr(Long attrgroupId, Map<String, Object> map) {
        //查看当前分组的信息，从分组信息里面获取当前分类的id
        //1、当前分组只能关联自己所属分类里面的属性
        PmsAttrGroupEntity attrGroupEntity = pmsAttrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //根据分类查询当前分类关联的分组
        //2、根据分组找到分组关联的属性
        //ne 不等于
        /**
         * 查询关联分类的分组
         */
        List<PmsAttrGroupEntity> pmsAttrGroupEntityList = pmsAttrGroupDao.selectList(new QueryWrapper<PmsAttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> collect = pmsAttrGroupEntityList.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        /**
         * 从关联表中  根据组id来查询对应的属性
         */
        List<PmsAttrAttrgroupRelationEntity> entities = pmsAttrAttrgroupRelationDao.selectList(new QueryWrapper<PmsAttrAttrgroupRelationEntity>().in("attr_group_id", collect));
        List<Long> collect1 = entities.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        QueryWrapper<PmsAttrEntity> queryWrapper = new QueryWrapper<PmsAttrEntity>().eq("catelog_id", catelogId).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(collect1!=null&& collect1.size()>0){
            queryWrapper.notIn("attr_id", collect1);
        }

        String key = (String) map.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and(item->{
                item.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<PmsAttrEntity> page = this.page(new Query<PmsAttrEntity>().getPage(map), queryWrapper);


        return new PageUtils(page);
    }

    @Override
    public void removeDetail(List<Long> asList) {
        this.removeByIds(asList);

        pmsAttrAttrgroupRelationDao.delete(new QueryWrapper<PmsAttrAttrgroupRelationEntity>().in("attr_id",asList));

    }


    /**
     * 指定的集合属性里面，挑出检索属性
     * @param collect1
     * @return
     */
    @Override
    public List<Long> selectSearchAttrs(List<Long> collect1) {
        List<Long> ids=this.baseMapper.selectSearchAttrs(collect1);
        return ids;
    }


}